package com.learn.sb.redis.reids.demo;

import com.learn.sb.redis.config.RedisConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;

/**
 * 手动创建 RedisConnectionFactory，RedisTemplate，没有让spring根据配置文件自动生成
 * 使用 RedisCallback 和 SessionCallback 一条命令执行多条指令
 */
public class SessionCallbackDemo {
	public static void main(String[] args) {
		ApplicationContext ctx = new AnnotationConfigApplicationContext(RedisConfig.class);
		RedisTemplate redisTemplate = ctx.getBean(RedisTemplate.class);

		SessionCallbackDemo demo = new SessionCallbackDemo();
		demo.useRedisCallback(redisTemplate);
		demo.useSeesionCallback(redisTemplate);

		demo.useRedisCallbackLambda(redisTemplate);
		demo.useSessionCallbackLambda(redisTemplate);
	}

	/**
	 * RedisCallback 接口不友好
	 * @param redisTemplate
	 */
	public void useRedisCallback(RedisTemplate redisTemplate) {
		redisTemplate.execute(new RedisCallback() {
			@Override
			public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
				Boolean res = redisConnection.set("aaasss2".getBytes(), "value111".getBytes());
				Boolean res2 = redisConnection.hSet("hash2".getBytes(), "field".getBytes(), "hvalue".getBytes());
				return res || res2;
			}
		});
	}

	/**
	 * 高级接口，比较友好，推荐使用 SessionCallback
	 * @param redisTemplate
	 */
	public void useSeesionCallback(RedisTemplate redisTemplate) {
		redisTemplate.execute(new SessionCallback() {
			@Override
			public Object execute(RedisOperations redisOperations) throws DataAccessException {
				redisOperations.opsForValue().set("aaasss21", "value222");
				redisOperations.opsForHash().put("hash21", "field222", "hvalue");
				return null;
			}
		});
	}

	/**
	 * 使用 lambda 表达式 调用 RedisCallback
	 */
	public void useRedisCallbackLambda(RedisTemplate redisTemplate) {
		redisTemplate.execute((RedisConnection rc) -> {
			Boolean res = rc.set("aaasss_lambda".getBytes(), "value111".getBytes());
			Boolean res2 = rc.hSet("hash_lambda".getBytes(), "field".getBytes(), "hvalue".getBytes());
			return res || res2;
		});
	}

	/**
	 * 使用 lambda 表达式 调用 SessionCallback
	 * 虽然可以执行，但IDE貌似不推荐，老是报错
	 */
	public void useSessionCallbackLambda(RedisTemplate redisTemplate) {
//		redisTemplate.execute((RedisOperations ro) -> {
//			ro.opsForValue().set("aaasss21_lambda", "value222");
//			ro.opsForHash().put("hash21_lambda", "field222", "hvalue");
//			return null;
//		});
	}


}
